package com.xuecheng.test.rabbitmq;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class Consumer02_subscibe_sms {
    //声明队列和交换机
    private static final String QUEUE_INFORM_SMS = "queue_inform_sms";
    private static final String EXCHANGE_FANOUT_INFROM = "exchange_fanout_infrom";

    public static void main(String[] args) {
        //创建连接
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("127.0.0.1");
        connectionFactory.setPort(5672);
        connectionFactory.setUsername("guest");
        connectionFactory.setPassword("guest");
        connectionFactory.setVirtualHost("/");

        Connection connection = null;
        Channel channel = null;
        try {
            //建立连接
            connection = connectionFactory.newConnection();
            //获取通道
            channel = connection.createChannel();
            //声明队列
            channel.queueDeclare(QUEUE_INFORM_SMS,true,false,false,null);
            //声明交换机
            /**交换机类型:
             *  fanout对应mq的publish/subscribe
             *  direct对应routing
             *  topic对应topics
             *  header对应headers
             *
             */
            channel.exchangeDeclare(EXCHANGE_FANOUT_INFROM, BuiltinExchangeType.FANOUT);

            //交换机和队列进行绑定
            channel.queueBind(QUEUE_INFORM_SMS,EXCHANGE_FANOUT_INFROM,"");

            //消费消息
            DefaultConsumer defaultConsumer = new DefaultConsumer(channel){
                @Override
                public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                    String message = new String(body,"utf-8");
                    System.out.println("reveive message :" + message);
                }
            };
            //监听队列
            channel.basicConsume(QUEUE_INFORM_SMS,true,defaultConsumer);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
